package com.example.trafficsystem.service;

import com.example.trafficsystem.entity.ExamRecord;
import com.example.trafficsystem.entity.Organization;
import com.example.trafficsystem.entity.Student;
import com.example.trafficsystem.entity.TrainingPlan;
import com.example.trafficsystem.repository.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.List;

@Service
public class StudentService {
    @Autowired
    private StudentRe studentRepository;

    @Autowired
    private OrganizationRe organizationRepository;
    @Autowired
    private TrainingPlanRe trainingPlanRepository;
    @Autowired
    private ExamRecordRe examRecordRepository;
    public String register(Student student) {
        Organization organization = organizationRepository.findById(student.getOrganization().getId()).orElse(null);
        if (organization == null) {
            return "组织不存在";
        }
        if (studentRepository.existsByPhone(student.getPhone())) {
            return "手机号已存在";
        }
        if (studentRepository.existsByEmail(student.getEmail())) {
            return "邮箱已存在";
        }
        Student newStudent = new Student();
        newStudent.setName(student.getName());
        newStudent.setPhone(student.getPhone());
        newStudent.setEmail(student.getEmail());
        newStudent.setPassword(student.getPassword());
        newStudent.setAddress(student.getAddress());
        newStudent.setOrganization(organization);
        studentRepository.save(newStudent);
        return "注册成功";
    }
    public boolean login(String account, String password){

        Student student= studentRepository.findByPhone(account);
        return student != null && student.getPassword().equals(password);
    }
    // 根据手机号查找学生
    public Student findByPhone(String phone) {
        return studentRepository.findByPhone(phone);
    }
    //加入培训计划
    @Transactional
    public Student joinTrainingPlan(Long studentId, Long trainingPlanId) {
        Student student = studentRepository.findById(studentId)
                .orElseThrow(()-> new RuntimeException("学生不存在"));
        TrainingPlan trainingPlan = trainingPlanRepository.findById(trainingPlanId)
                .orElseThrow(()-> new RuntimeException("培训计划不存在"));
        // 如果学生已有培训计划，先退出当前培训计划
        if (student.getTrainingPlan() != null) {

            student.setTrainingPlan(null);  // 解除当前培训计划
        }
        student.setTrainingPlan(trainingPlan);
        return studentRepository.save(student);
    }

}
